//
//  OAuthViewController.swift
//  SwiftWeiBo
//
//  Created by wyw on 16/10/9.
//  Copyright © 2016年 Style_Y. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController {

    let WB_App_Key = "1690500587"
    let WB_App_Secret = "24851414e7782c90a6b5aed0a7098296"
    let WB_redirect_uri = "http://v-hudong.com"
    
    override func loadView() {
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupNAV()
        
        loadPage()
    }
    
    private func setupNAV() {
      navigationItem.title = "授权页面"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.plain, target: self, action: #selector(OAuthViewController.close))
        
    }
    
    // 关闭页面
    @objc fileprivate func close() {
      dismiss(animated: true, completion: nil)
    }
    
    // 加载页面
    private func loadPage() {
        // 1.获取未授权的RequestToken
        // 要求SSL1.2
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_App_Key)&redirect_uri=\(WB_redirect_uri)"
        let url = URL(string: urlStr)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }

    // MARK: - 懒加载
    fileprivate lazy var webView : UIWebView = {
        let wv = UIWebView()
        wv.delegate = self
        return wv
    }()

}

extension OAuthViewController : UIWebViewDelegate
{
    public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        print(request.url?.absoluteString)
        
        let loadUrl = request.url!.absoluteString
        
        // 1.判断是否授权回调页面，如果不是就加载
        if !loadUrl.hasPrefix(WB_redirect_uri)
        {
            return true
        }
        
        let codeStr = "code="
        // 2.判断是否授权成功
        if (request.url?.query?.hasPrefix(codeStr))! {
            // 1.授权成功 取出已经授权的requestToken
            let code = request.url?.query?.substring(from: codeStr.endIndex)
            // 2.利用已经授权的RequestToken换取AccessToken
            loadAccessToken(code!)
            
        } else {
            // 授权失败 关闭页面
            close()
        }
        
        return false
    }
    
    // 换取AccessToken 
      // 参数 已经授权的requestToken
    private func loadAccessToken(_ code : String) {
        
        // 1.定义路径
        let path = "oauth2/access_token"
        // 2.封装参数
        let params = ["client_id":WB_App_Key, "client_secret":WB_App_Secret, "grant_type":"authorization_code", "code":code, "redirect_uri":WB_redirect_uri]
        // 3.Post请求
        NetWorkTools.shareNetWorkTools().post(path, parameters: params, progress: nil, success: { (_, JSON) in

            let account =  UserAccount.init(dict: JSON as! [String : AnyObject])
            
            // 获取用户信息
            account.loadUserInfo({ (account, error) in
                
                if account != nil {
                    // 保存
                    account?.saveAccount()
                    // 去欢迎界面
                    NotificationCenter.default.post(name: NSNotification.Name(rawValue: SwitchRootViewControllerKey), object: false)
                    print(account)
                }
            })
           
            
            }) { (_, error) in
                
                print(error)
        }
    }
    
    func webViewDidStartLoad(_ webView: UIWebView)
    {
        SVProgressHUD.show(withStatus: "正在加载")
        SVProgressHUD.setDefaultMaskType(SVProgressHUDMaskType.black)
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    // 加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error)
    {
        SVProgressHUD.dismiss()
        print(error)
    }
}

